<script setup name="Oss" lang="ts">
import { CloudDownloadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import { parseTime } from '../../../utils/ruoyi.ts'
import { delOss, listOss } from '@/api/system/oss'
import ImagePreview from '@/components/ImagePreview/index.vue'
import type { OssForm, OssQuery, OssVO } from '@/api/system/oss/types'
import { getConfigKey, updateConfigByKey } from '@/api/system/config/index.ts'
import download from '~/plugins/download.ts'

const router = useRouter()
const message = useMessage()
const modal = useModal()
const ossList = ref<OssVO[]>([])
const showTable = ref(true)
const buttonLoading = ref(false)
const loading = ref(true)
const ids = ref<Array<string | number>>([])
const total = ref(0)
const type = ref(0)
const previewListResource = ref(true)

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

// 默认排序
const defaultSort = ref({ prop: 'createTime', order: 'ascending' })

const ossFormRef = ref()
const queryFormRef = ref()

const initFormData = {
  file: undefined,
}
const data = reactive<PageData<OssForm, OssQuery>>({
  form: { ...initFormData },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fileName: '',
    originalName: '',
    fileSuffix: '',
    createTime: '',
    service: '',
    orderByColumn: defaultSort.value.prop,
    isAsc: defaultSort.value.order,
  },
  rules: {
    file: [
      { required: true, message: '文件不能为空', trigger: 'blur' },
    ],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询OSS对象存储列表 */
async function getList() {
  loading.value = true
  const res = await getConfigKey('sys.oss.previewListResource')
  previewListResource.value = res?.data === undefined ? true : res.data === 'true'
  const response = await listOss(queryParams.value)
  ossList.value = response.rows
  total.value = response.total
  loading.value = false
  showTable.value = true
}

function checkFileSuffix(fileSuffix: string[]) {
  const arr = ['png', 'jpg', 'jpeg']
  return arr.some((type) => {
    return fileSuffix.includes(type)
  })
}

/** 取消按钮 */
function cancel() {
  dialog.visible = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  ossFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  showTable.value = false
  queryFormRef.value?.resetFields()
  queryParams.value.orderByColumn = defaultSort.value.prop
  queryParams.value.isAsc = defaultSort.value.order
  handleQuery()
}

/** 任务日志列表查询 */
function handleOssConfig() {
  router.push('/system/oss-config/index')
}

/** 文件按钮操作 */
function handleFile() {
  reset()
  type.value = 0
  dialog.visible = true
  dialog.title = '上传文件'
}

/** 图片按钮操作 */
function handleImage() {
  reset()
  type.value = 1
  dialog.visible = true
  dialog.title = '上传图片'
}

/** 提交按钮 */
function submitForm() {
  dialog.visible = false
  getList()
}

/** 下载按钮操作 */
function handleDownload(row: OssVO) {
  download.oss(row.ossId)
}

/** 用户状态修改  */
async function handlePreviewListResource(preview: boolean) {
  const text = preview ? '启用' : '停用'
  try {
    modal.confirm({
      title: `确认要"${text}""预览列表图片"配置吗?`,
      onOk: async () => {
        updateConfigByKey('sys.oss.previewListResource', preview)
        await getList()
        message.success(`${text}成功`)
      },
    })
  }
  catch {
  }
}

/** 删除按钮操作 */
async function handleDelete(row?: OssVO) {
  const ossIds = row?.ossId || ids.value
  modal.confirm({
    title: `是否确认删除OSS对象存储编号为"${ossIds}"的数据项?`,
    onOk: async () => {
      loading.value = true
      await delOss(ossIds).finally(() => loading.value = false)
      await getList()
      message.success('删除成功')
    },
  })
}
const fileList = ref([])
async function onSuccess(saveFileList) {
  fileList.value = saveFileList
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card shadow="hover" class="mb-20px">
      <div class="flex-between">
        <div>
          <a-form
            ref="queryFormRef" class="inline-form" :model="queryParams" layout="inline" :label-col="{ style: 'width:68px' }"
            label-width="68px"
          >
            <a-form-item label="原名" prop="originalName">
              <a-input
                v-model:value="queryParams.originalName" placeholder="请输入原名" clearable style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="文件后缀" prop="fileSuffix">
              <a-input
                v-model:value="queryParams.fileSuffix" placeholder="请输入文件后缀" clearable style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="服务商" prop="service">
              <a-input
                v-model:value="queryParams.service" placeholder="请输入服务商" clearable style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="mr-10px" @click="handleQuery">
                搜索
              </a-button>
              <a-button @click="resetQuery">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10">
            <a-col>
              <a-button v-hasPermi="['system:oss:upload']" type="primary" @click="handleFile">
                上传文件
              </a-button>
            </a-col>
            <a-col>
              <a-button v-hasPermi="['system:oss:upload']" type="primary" @click="handleImage">
                上传图片
              </a-button>
            </a-col>

            <a-col>
              <a-button
                v-hasPermi="['system:oss:edit']"
                @click="handlePreviewListResource(!previewListResource)"
              >
                预览开关 :
                {{
                  previewListResource ? "禁用" : "启用"
                }}
              </a-button>
            </a-col>
            <a-col>
              <a-button v-hasPermi="['system:oss:list']" @click="handleOssConfig">
                配置管理
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-card shadow="hover">
      <a-table
        :loading="loading"
        :data-source="ossList"
        :pagination="false"
      >
        <a-table-column title="文件名" align="center" data-index="fileName" />
        <a-table-column title="原名" align="center" data-index="originalName" />
        <a-table-column title="文件后缀" align="center" data-index="fileSuffix" />
        <a-table-column title="文件展示" align="center" data-index="url">
          <template #default="{ record }">
            <ImagePreview
              v-if="previewListResource && checkFileSuffix(record.fileSuffix)"
              :width="100"
              :height="100"
              :src="record.url"
              :preview-src-list="[record.url]"
            />
            <span v-if="!checkFileSuffix(record.fileSuffix) || !previewListResource" v-text="record.url" />
          </template>
        </a-table-column>
        <a-table-column title="创建时间" align="center" prop="createTime" width="180" sortable="custom">
          <template #default="{ record }">
            <span>{{ parseTime(record.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </a-table-column>
        <a-table-column title="上传人" align="center" data-index="createByName" />
        <a-table-column title="服务商" align="center" data-index="service" sortable="custom" />
        <a-table-column title="操作" align="center" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-tooltip content="下载" placement="top">
              <a-button
                v-hasPermi="['system:oss:download']" type="link"
                @click="handleDownload(record)"
              >
                <CloudDownloadOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button
                v-hasPermi="['system:oss:remove']" type="link"
                @click="handleDelete(record)"
              >
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-5">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>
    <!-- 添加或修改OSS对象存储对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="500px" append-to-body>
      <a-form ref="ossFormRef" :model="form" :rules="rules" label-width="80px">
        <a-form-item label="文件名">
          <fileUpload v-if="type === 0" v-model="form.file" />
          <imageUpload v-if="type === 1" v-model="form.file" />
          <oss-file-upload v-if="type === 2" v-model="form.file" @success="onSuccess" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button :loading="buttonLoading" type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
